package com.tinyideatech.admin.controller.car;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.common.core.entity.PageResult;
import com.tinyideatech.common.core.text.Convert;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.system.entity.CarGoods;
import com.tinyideatech.system.service.ICarGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author zhangy-5
 * @date 2020-04-07
 */

@Controller
@RequestMapping("/car/goods")
public class CarGoodsController extends BaseController {

    @Autowired
    private ICarGoodsService carGoodsService;

    @GetMapping()
    public String list() {
        return "car/goods/list";
    }

    @GetMapping("/add")
    public String add() {
        return "car/goods/add";
    }

    @GetMapping("/edit/{id}")
    public String carGoodsEdit(
            @PathVariable("id") Long id,
            ModelMap map
    ) {
        CarGoods carGoods = carGoodsService.getById(id);
        map.addAttribute("carGoods", carGoods);
        return "car/goods/edit";
    }

    @ResponseBody
    @PostMapping("/list")
    public PageResult list(CarGoods carGoods) {
        QueryWrapper<CarGoods> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(carGoods.getName())) {
            qw.like("name", carGoods.getName());
        }
        IPage<CarGoods> page = startPage();
        IPage<CarGoods> carGoodsList = carGoodsService.page(page, qw);
        return page(carGoodsList);
    }

    @ResponseBody
    @PostMapping("/save")
    public ApiResult save(
            CarGoods sysRole
    ) {
        CarGoods carGoods = carGoodsService.list(new QueryWrapper<CarGoods>().eq("name", sysRole.getName())).get(0);
        if (carGoods != null) {
            return error();
        }
        System.out.println(sysRole);
        carGoodsService.saveOrUpdate(sysRole);
        return success();
    }

    @ResponseBody
    @PostMapping("/remove")
    public ApiResult remove(
            String ids
    ) {
        Long[] carGoodsIds = Convert.toLongArray(ids);
        carGoodsService.removeByIds(Arrays.asList(carGoodsIds));
        return success();
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public ApiResult changeStatus(CarGoods carGoods) {
        carGoodsService.changeStatus(carGoods);
        return success();
    }

}
